package com.weilx959.spt.app.utils;

import com.weilx959.spt.app.constants.AppConstants;
import com.weilx959.spt.app.context.ConfigContext;
import com.weilx959.spt.app.model.AppConfig;
import com.weilx959.spt.core.StageContext;
import com.weilx959.spt.core.constants.CommonConstants;
import com.weilx959.spt.core.constants.ThemeEnum;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class StylesheetUtil {
    private StylesheetUtil() {}

    /**
     * 添加样式表
     *
     * @param stylesheets 样式表
     */
    public static void addStylesheets(List<String> stylesheets) {
        addStylesheets(stylesheets, Optional.ofNullable(ConfigContext.get())
            .map(AppConfig::getGeneral)
            .map(AppConfig.General::getTheme)
            .orElse(CommonConstants.DEFAULT_THEME));
    }

    /**
     * 添加样式表
     *
     * @param stylesheets 样式表
     * @param theme       主题
     */
    public static void addStylesheets(List<String> stylesheets, ThemeEnum theme) {
        if (CollectionUtils.isEmpty(stylesheets) || Objects.isNull(theme)) {
            return;
        }
        final List<String> defaultStylesheets = List.of(AppConstants.BASE_STYLE_FILE, theme.getStyle());
        Iterator<String> stylesheetIter = StageContext.get()
            .getScene()
            .getStylesheets()
            .iterator();

        // 移除已加载的插件样式
        while (stylesheetIter.hasNext()) {
            if (defaultStylesheets.contains(stylesheetIter.next())) {
                continue;
            }
            stylesheetIter.remove();
        }
        // 添加新增的插件样式
        StageContext.get().getScene().getStylesheets().addAll(stylesheets);
    }
}
